package com.sky.sky_server.service.impl;

import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sky.sky_common.config.WeChatProperties;
import com.sky.sky_common.exception.UserLoginException;
import com.sky.sky_common.util.HttpClientUtil;
import com.sky.sky_pojo.dto.UserLoginDTO;
import com.sky.sky_pojo.entity.User;
import com.sky.sky_server.mapper.UserMapper;
import com.sky.sky_server.service.UserService;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    private final static String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    /**
     * 微信登录
     * @param userfLoginVO
     */
    public User wxLogin(UserLoginDTO userLoginDTO){
        // 调用微信服务接口，获取openid
        String response = getOpenid(userLoginDTO);
        if(response == null)
            return null;

        JSONObject json = JSON.parseObject(response);
        String openid = json.getString("openid");
        // 判断openid是否存在,不存在就抛出异常
        if(openid == null){
            throw new UserLoginException();
        }

        // 与数据库的交互，新用户？老用户？
        User user = userMapper.selectByOpenid(openid);
        if(user == null){
            // 新用户，注册用户
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        // 返回用户对象信息
        return user;
    }

    private String getOpenid(UserLoginDTO userLoginDTO){
        Map<String, String> map = Map.of(
            "appid", weChatProperties.getAppid(),
            "secret", weChatProperties.getSecret(),
            "js_code", userLoginDTO.getCode(),
            "grant_type", "authorization_code"
        );
        String response = null;
        try {
            response = HttpClientUtil.get(HttpClientUtil.buildUrlWithParams(WX_LOGIN, map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
    
}
